<template>
  <div class="entry-information-item">
    <div class="entry-header-title">
      <div class="title">入职信息</div>
      <div>
        <span class="title">入职情况：</span>
        <span v-if="infoData.status == 'waiting'" style="margin: 0 10px">
          <el-button type="success" @click="operate('success')"
            >审核通过</el-button
          >
          <el-button type="danger" @click="operate('fail')">审核失败</el-button>
        </span>
        <el-tag v-if="infoData.status == 'waiting'" type="warning">待审核</el-tag>
        <el-tag v-if="infoData.status == 'sign'" type="info">待签署</el-tag>
        <el-tag v-if="infoData.status == 'success'" type="success">审核成功</el-tag>
        <el-tag v-if="infoData.status == 'fail'" type="danger">审核失败</el-tag>
      </div>
    </div>
    <div class="entry-information-container">
      <el-descriptions class="margin-top" :column="4" border>
        <el-descriptions-item
          v-for="(item, index) in userInterviewInfo"
          :key="index"
        >
          <template slot="label">{{ item.label }}</template>
          <div
            class="look-user-info"
            @click="lookFile(item)"
            v-if="item.value == '点击查看'"
          >
            {{ item.value }}<i class="el-icon-view" />
          </div>
          <div v-else>{{ item.value }}</div>
        </el-descriptions-item>
      </el-descriptions>
    </div>

    <el-dialog :visible.sync="emergencyVisible" title="确认信息" width="30%">
        <template v-if="isSuccess">
            <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="宿舍" v-if="infoData.isquarter === 1">
            <el-cascader v-model="form.roomID" style="width:100%;" 
            :options="roomFormatter" placeholder="选择宿舍" />
          </el-form-item>
          <el-form-item label="培训">
            <el-select v-model="form.needCourse" style="width: 100%;" placeholder="请选择是否需要培训">
              <el-option v-for="item in needCourseOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="课程">
            <el-select v-model="form.courseIDs" multiple style="width: 100%;" placeholder="请选择课程"
              :disabled="form.needCourse !== 1">
              <el-option v-for="item in courseOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" :loading="btnLoading" @click="post">确 定</el-button>
        </span>
        </template>
        <template v-else>
            <el-form ref="form" :model="refuseForm" label-width="120px">
                <el-form-item label="拒绝理由">
                    <el-input v-model="refuseForm.fail_reason" type="textarea" :rows="4" />
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="refuseConfirm">确 定</el-button>
            </span>
        </template>
      </el-dialog>
  </div>
</template>
<script>
import { course } from '@/api/train'
import { getDormitory } from '@/api/v2/basic'
import { examineEntry } from '@/api/v2/entry'

import { handleFiledData,mapFields } from '@/utils/handleData'
export default {
  props: {
    infoData:{
        type:Object,
        default:{}
    },
    fetchEntryList:{
        type:Function
    },
    fieldList:{
        type:Array,
        default:[]
    }
  },
  data() {
    return {
        courseOptions: [],
        dormitory: [],
        isSuccess:false,
        emergencyVisible:false,
        form: {
            roomID: '',
            needCourse: '',
            courseIDs: '',
            data:{
            }
      },
      refuseForm: {
        fail_reason: ''
      },
      needCourseOptions: [
        { label: '是', value: 1 },
        { label: '否', value: 0 }
      ],
      btnLoading:false
    };
  },
  methods: {
    operate(val) {
        if (val==="success") {
            this.getAllInfo()
            this.isSuccess=true
        } else {
            this.isSuccess=false
        }
        this.emergencyVisible=true
    },
    lookFile(item) {
      this.$emit("lookFile", item);
    },
    async getCourses() {
      const { data } = await course({paginate: 1000})
      this.courseOptions = data.map(item => {
          return {
            label: item.title,
            value: item.id,
          }
       })
    },
    async getDormitoryInfo(){
        const { data } = await getDormitory()
        this.dormitory = data
    },
    async getAllInfo(){
        try {
            await Promise.all([
                this.getCourses(),
                this.getDormitoryInfo()
            ])
        } catch (error) {
            console.log(error,'error');
        }
    },
    handelRoomID(room) {
      if (Array.isArray(room) && room.length > 0) {
        return room[room.length - 1]
      } else {
        return room
      }
    },
    async post(){
        const { courseIDs, needCourse, roomID} = this.form
        this.form.data.room_id =this.handelRoomID(roomID)
        this.form.data = mapFields(this.form.data, this.fieldList)
        const params = {
            agree: 1,
            id: this.$route.params?.id,
            needCourse: needCourse,
            course_id: JSON.stringify(courseIDs),
            data:JSON.stringify(this.form.data)
        }
        console.log(params, 'params');
        this.entryApi(params)
    },
    refuseConfirm() {
      const { fail_reason } = this.refuseForm
      const params = {
        agree: 0,
        id: this.$route.params?.id,
        fail_reason: fail_reason
      }
      this.entryApi(params)
    },
    async entryApi(params) {
      this.btnLoading=true
      try {
        await examineEntry(params)
        this.fetchEntryList()
        // this.getUserEntry()
        this.$message.success('审核成功')
        this.emergencyVisible = false
      } catch (error) {
        this.$message.error(error.response?.data?.message ?? '修改失败')
      }finally{
        this.btnLoading=false
      }
    }
  },
  computed: {
    userInterviewInfo() {
      return this.infoData.handleArr;
    },
    roomFormatter() {
      if (!Array.isArray(this.dormitory)) { return [] }

      return this.dormitory.map(item => {
        const { address, id, room } = item

        let children = []
        let isDisabled = true

        if (Array.isArray(room) && room.length > 0) {
          isDisabled = false
          children = room.map(r => {
            const available = r.number - (r.userCompany?.length ?? 0)
            return { label: r.name, value: r.id, disabled: available <= 0 }
          })
        }

        return {
          label: address,
          value: id,
          disabled: isDisabled,
          children
        }
      })
    },
  },
};
</script>
<style lang="scss" scoped>
.entry-information-item {
  .entry-header-title {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .title {
      font-size: 16px;
      font-weight: bold;
      margin: 20px 0;
      padding-right: 20px;
    }
  }

  .entry-information-container {
    .look-user-info {
      color: #1890ff;
      cursor: pointer;
    }
  }
}
</style>
